package com.djinquan.common.service.impl;

import com.djinquan.common.service.RedissonService;
import com.djinquan.common.util.FunUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * @Desc:
 * @Group:美的集团-营销系统-技术组
 * @Author dengjq15
 * @Date 2023/8/6
 */
@Service("redissonService")
public class RedissonServiceImpl implements RedissonService {

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public Object executeWithLockThrows(String key, int waitTime, int leaseTime, TimeUnit timeUnit, ProceedingJoinPoint joinPoint) throws Throwable {
        RLock lock = redissonClient.getFairLock(key);
        boolean lockSuccess = false;
        if(leaseTime<1){
            lockSuccess = lock.tryLock(waitTime,timeUnit);
        }
        else{
            lockSuccess = lock.tryLock(waitTime,leaseTime,timeUnit);
        }
        if(!lockSuccess){

        }
        try{
           return joinPoint.proceed();
        }
        finally{
            if(lock.isLocked()&&lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }
}
